import { InputManager } from '@/core/InputManager';
import { ChatUI } from './ChatUI';

export class EnhancedInputHandler {
    private inputManager: InputManager;
    private chatUI: ChatUI;
    private lastEnterKeyTime = 0;
    private lastEscKeyTime = 0;
    private keyDebounceDelay = 200; // 200ms debounce to prevent rapid key presses
    private enterKeyPressed = false;
    private escKeyPressed = false;

    constructor(inputManager: InputManager, chatUI: ChatUI) {
        this.inputManager = inputManager;
        this.chatUI = chatUI;
        this.setupEventListeners();
    }

    private setupEventListeners(): void {
        // Listen for chat input focus/blur events to manage game input
        document.addEventListener('chatInputFocus', () => {
            this.onChatInputFocus();
        });

        document.addEventListener('chatInputBlur', () => {
            this.onChatInputBlur();
        });
    }

    private onChatInputFocus(): void {
        // When chat input is focused, we might want to disable some game controls
        // This is handled by the game's input processing logic
        console.log('Chat input focused - game input partially disabled');
    }

    private onChatInputBlur(): void {
        // When chat input loses focus, re-enable game controls
        console.log('Chat input blurred - game input re-enabled');
    }

    /**
     * Handle Enter key logic based on chat box state and input content
     */
    public handleEnterKey(): void {
        const currentTime = Date.now();
        
        // Debounce to prevent rapid key presses
        if (currentTime - this.lastEnterKeyTime < this.keyDebounceDelay) {
            return;
        }
        this.lastEnterKeyTime = currentTime;

        const isChatVisible = this.chatUI.getIsVisible();
        
        if (!isChatVisible) {
            // Chat box is not visible - show it and focus input
            this.showChatBoxAndFocus();
        } else {
            // Chat box is visible - check input content
            const hasContent = this.hasInputContent();
            
            if (hasContent) {
                // Input has content - send the message
                this.chatUI.sendCurrentMessage();
                
                // After sending, clear input and keep focus
                setTimeout(() => {
                    this.clearInput();
                    this.focusInput();
                }, 10);
            } else {
                // Input is empty - hide chat box
                this.hideChatBox();
            }
        }
    }

    /**
     * Handle ESC key to hide chat box
     */
    public handleEscapeKey(): void {
        const currentTime = Date.now();
        
        // Debounce to prevent rapid key presses
        if (currentTime - this.lastEscKeyTime < this.keyDebounceDelay) {
            return;
        }
        this.lastEscKeyTime = currentTime;

        const isChatVisible = this.chatUI.getIsVisible();
        
        if (isChatVisible) {
            this.hideChatBox();
        }
    }

    /**
     * Check if chat box is currently visible
     */
    public isChatBoxVisible(): boolean {
        return this.chatUI.getIsVisible();
    }

    /**
     * Check if input box has content
     */
    public hasInputContent(): boolean {
        const inputElement = this.getInputElement();
        return inputElement ? inputElement.value.trim().length > 0 : false;
    }

    /**
     * Show chat box and focus input
     */
    public showChatBoxAndFocus(): void {
        this.chatUI.show();
        this.focusInput();
    }

    /**
     * Hide chat box
     */
    public hideChatBox(): void {
        this.chatUI.hide();
    }

    /**
     * Focus the input box
     */
    public focusInput(): void {
        const inputElement = this.getInputElement();
        if (inputElement) {
            // Small delay to ensure the chat box is fully shown
            setTimeout(() => {
                inputElement.focus();
            }, 50);
        }
    }

    /**
     * Clear input box content
     */
    public clearInput(): void {
        const inputElement = this.getInputElement();
        if (inputElement) {
            inputElement.value = '';
        }
    }

    /**
     * Update method to be called in the game loop
     */
    public update(): void {
        // Handle Enter key with proper state tracking
        const enterPressed = this.inputManager.isKeyPressed('Enter') || this.inputManager.isKeyPressed('NumpadEnter');
        if (enterPressed && !this.enterKeyPressed) {
            this.handleEnterKey();
        }
        this.enterKeyPressed = enterPressed;

        // Handle ESC key for chat with proper state tracking
        const escPressed = this.inputManager.isKeyPressed('Escape');
        if (escPressed && !this.escKeyPressed && this.isChatBoxVisible()) {
            this.handleEscapeKey();
        }
        this.escKeyPressed = escPressed;
    }

    /**
     * Get the chat input element
     */
    private getInputElement(): HTMLInputElement | null {
        return document.querySelector('.chat-input') as HTMLInputElement;
    }

    /**
     * Setup enhanced message sending behavior
     */
    public setupEnhancedMessageSending(): void {
        // The enhanced input handling is now done in the handleEnterKey method
        // This method is kept for any additional setup if needed
        console.log('Enhanced input handler initialized');
    }

    /**
     * Initialize the enhanced input handler
     */
    public initialize(): void {
        // Setup enhanced message sending behavior
        // Wait a bit to ensure ChatUI is fully initialized
        setTimeout(() => {
            this.setupEnhancedMessageSending();
        }, 100);
    }

    /**
     * Check if we should process keyboard input
     * Returns false if chat input is focused or other UI is active
     */
    public shouldProcessGameInput(): boolean {
        const inputElement = this.getInputElement();
        const isChatInputFocused = inputElement === document.activeElement;
        
        // Don't process game input if chat input is focused
        return !isChatInputFocused;
    }

    /**
     * Get the current chat UI instance
     */
    public getChatUI(): ChatUI {
        return this.chatUI;
    }

    /**
     * Dispose of event listeners
     */
    public dispose(): void {
        document.removeEventListener('chatInputFocus', this.onChatInputFocus);
        document.removeEventListener('chatInputBlur', this.onChatInputBlur);
    }
}